<template>
  <div>
    <div class="gstc-wrapper" ref="gstcElement"></div>
    <Model
      :submit="submit"
      :afterClose="afterClose"
      :isopen="store.isModelShow"
    />
  </div>
</template>

<script>
import { html } from "lit";
import { nextTick } from "vue";

import { Plugin as TimelinePointer } from "gantt-schedule-timeline-calendar/dist/plugins/timeline-pointer.esm.min.js";
import { Plugin as Selection } from "gantt-schedule-timeline-calendar/dist/plugins/selection.esm.min.js";
import { Plugin as ItemResizing } from "gantt-schedule-timeline-calendar/dist/plugins/item-resizing.esm.min.js";
import { Plugin as ItemMovement } from "gantt-schedule-timeline-calendar/dist/plugins/item-movement.esm.min.js";
import { Plugin as HighlightWeekends } from "gantt-schedule-timeline-calendar/dist/plugins/highlight-weekends.esm.min";
import { Plugin as CalendarScroll } from "gantt-schedule-timeline-calendar/dist/plugins/calendar-scroll.esm.min";
import { Plugin as DependencyLines } from "gantt-schedule-timeline-calendar/dist/plugins/dependency-lines.esm.min";
import { Plugin as ItemTypes } from "gantt-schedule-timeline-calendar/dist/plugins/item-types.esm.min";
import "gantt-schedule-timeline-calendar/dist/style.css";
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import GSTC from "gantt-schedule-timeline-calendar/dist/gstc.wasm.esm.min.js";
import Model from "./Model.vue";
import { store } from "@/store.js";
import { generate, getRootData } from "@/controller/api.js";
import {
  chartTimelineGridRowCellTemplate,
  listColumnRowTemplate,
  chartTimelineItemsTemplate,
  chartTimelineItemsRowItemTemplate,
} from "@/config/GSTCTemplete.js";
import { date } from "@/utils/global.js";
import { updateMethod, changePath } from "../controller/api";
const GSTCID = GSTC.api.GSTCID;

function itemsSlot(vido) {
  return (content) =>
    vido.html`<div
        class="my-items-slot"
      >
      <div class="my-item-slot-content">${content}</div>
      </div>`;
}

const itemMovementOptions = {
  threshold: {
    horizontal: 25,
  },
  dependant: false,
  moveDependantVertically: false,
  snapToTime: {
    start({ startTime }) {
      return startTime;
    },
    end({ endTime }) {
      return endTime;
    },
  },
  events: {
    onEnd({ state, items }) {
      items.after.map((item, index) => {
        let time;
        state.update(
          "config.list.rows." + item.rowId + ".taskTime",
          (oldLabel) => {
            time = oldLabel;
            return oldLabel;
          }
        );
        state.update(
          "config.list.rows." + item.rowId + ".startTime",
          (oldLabel) => {
            return GSTC.api.date(new Date(item.time.start));
          }
        );
        state.update(
          "config.list.rows." + item.rowId + ".endTime",
          (oldLabel) => {
            return GSTC.api.date(new Date(item.time.start)).add(time, "day");
          }
        );
      });
      return items.after;
    },
  },
};

export default {
  name: "GSTC",
  components: {
    Model: Model,
  },
  data() {
    return {
      store,
      renderComponent: true,
    };
  },
  props: ["configData"],
  methods: {
    forceRerender() {
      this.renderComponent = false;
      nextTick(() => {
        this.renderComponent = true;
      });
    },
  },
  setup(props, a) {
    let gstc, state;
    const gstcElement = ref(null);
    const { configData } = props;
    onMounted(async () => {
      // const { rows, items } = generate(configData);
      const { rows, items } = await getRootData();
      console.log(rows);
      console.log(items);
      console.log("mount");
      const config = {
        licenseKey:
          "====BEGIN LICENSE KEY====\nU+XB1UVIPfgbIyljExtfHkCw6/YF2fTSc5levxKfyMgmYqeb6b4ZSGjFvG1M4Ouksn26PEy/Ra6RjkpJj2Oc8ZrnKTE7c/CyjBA8ZtnJxmKo0ON4MI8aOaR9qCRxJ40dR8eq/hMhRclIJFcVJGNoCPBWwHu6jCZRnvQeVWLpJqmeZvU3MgEZaPNOj3kEpEUBF7cPObKUaKTrWbn2ljeqFlcTtEwQOOulSPIGF8mdCzlASh9wMnx1Zr2CIk3a9H+mOoqM9fpgihfcyJhdW638WYUQZNmsnJ2KgcQnIIa3AH8TJqPS2sBH8MaVJu+9s96z/GWHvHkVXC2vPvOXRrJ/Cg==||U2FsdGVkX1+r2pkfoZVVq3ktHEXJsmEvc2qjF0mGmP7I3kQLsFkNIiKvSOWh612cHRKQWXTTUX+Nv/F8nVmsC0e8bSqwfMKS0htgoohEjFw=\nAY/8+PH+xmj1j1KZSYKjMRkI2b3/LWYw8FjIa/+Gs4MYBFzx+fd+VacylM5LoIoOqvELtuf57rbw37dHDK9AbBuVjq/TKFrDj9SzOVPGstjHXsOKRnWwhV6l8bDLDaaBoFLBwsaEGa9N+GpN+qpUbICvgJoPaYmL/GvD4LiQSGPnW19sxJXAJnZYcakhg8Ds4imYthENUNJGotFCjhaISQRZXM9VyXN/IuuAcq9uuY3k2UPf4xrd97kqpaXZ5F2xPlESgrBKT0GZ+9tAjLVAaX34wh0AyAl0xJuBFVqHftfv4LNgeyrVUNswrVxqrRsMarBpWRyygdk/qgpZGZmERQ==\n====END LICENSE KEY====",
        innerHeight: 650,
        plugins: [
          TimelinePointer(),
          Selection(),
          //ProgressBar(),
          HighlightWeekends(),
          DependencyLines({
            type: "square",
            onLine: [
              (line) => {
                if (
                  (line.fromItem.id == GSTCID("90") &&
                    line.toItem.id == GSTCID("93")) ||
                  (line.fromItem.id == GSTCID("93") &&
                    line.toItem.id == GSTCID("96")) ||
                  (line.fromItem.id == GSTCID("96") &&
                    line.toItem.id == GSTCID("98")) ||
                  (line.fromItem.id == GSTCID("98") &&
                    line.toItem.id == GSTCID("99"))
                )
                  line.className = [
                    "gstc__chart-timeline-dependency-lines-lines-line ",
                    " my_line",
                  ];
                return line;
              },
            ],
            onLines: [
              (lines) => {
                lines.map((item) => {
                  if (item.points.length == 0) {
                    return item;
                  } else if (item.points.length == 2) {
                    item.points[1].content = html`<div
                      class="arr_right"
                    ></div>`;
                  } else if (
                    item.points.length == 3 &&
                    item.points[2].y > item.points[0].y
                  ) {
                    item.points[2].content = html`<div class="arr_down"></div>`;
                  } else if (
                    item.points.length == 3 &&
                    item.points[2].y < item.points[0].y
                  ) {
                    item.points[2].content = html`<div class="arr_up"></div>`;
                  } else if (
                    item.points.length == 5 &&
                    item.points[4].y > item.points[0].y
                  ) {
                    item.points[4].content = html`<div class="arr_down"></div>`;
                  } else if (
                    item.points.length == 5 &&
                    item.points[4].y < item.points[0].y
                  ) {
                    item.points[4].content = html`<div class="arr_up"></div>`;
                  }
                  return item;
                });

                return lines;
              },
              (lines) => {
                lines.map((item) => {
                  const { lineContent } = item.fromItem;
                  const lineArr = lineContent.split("-");
                  if (item.points.length == 0) return item;
                  else {
                    item.points[0].content = html`<div class="my_line_text1">
                        <p>${lineArr[0]}</p>
                      </div>
                      <div class="my_line_text2">
                        <p>${lineArr[1]}</p>
                      </div>`;
                  }
                });
                return lines;
              },
            ],
          }),
          ItemMovement(itemMovementOptions),
        ],
        list: {
          columns: {
            data: {
              [GSTC.api.GSTCID("id")]: {
                id: GSTC.api.GSTCID("id"),
                width: 60,
                data: ({ row }) => GSTC.api.sourceID(row.id),
                header: {
                  content: "ID",
                },
              },
              [GSTC.api.GSTCID("task")]: {
                id: GSTC.api.GSTCID("task"),
                width: 240,
                data: "task",
                expander: true,
                header: {
                  content: "工作名称",
                },
              },
              [GSTC.api.GSTCID("startTime")]: {
                id: GSTC.api.GSTCID("startTime"),
                width: 100,
                data: ({ row }) => {
                  return GSTC.api.date(row.startTime).format("YYYY-MM-DD");
                },
                header: {
                  content: "计划开始",
                },
              },
              [GSTC.api.GSTCID("endTime")]: {
                id: GSTC.api.GSTCID("endTime"),
                width: 100,
                data: ({ row }) => {
                  return GSTC.api.date(row.endTime).format("YYYY-MM-DD");
                },
                header: {
                  content: "计划完成",
                },
              },
              [GSTC.api.GSTCID("taskTime")]: {
                id: GSTC.api.GSTCID("taskTime"),
                width: 60,
                data: "taskTime",
                header: {
                  content: "工期",
                },
              },
              [GSTC.api.GSTCID("prepath")]: {
                id: GSTC.api.GSTCID("prepath"),
                width: 60,
                data: "prepath",
                header: {
                  content: "前置任务",
                },
              },
            },
          },
          rows: rows,
        },
        chart: {
          items: items,
        },
        slots: {
          "chart-timeline-items-row-item": { content: [itemsSlot] },
          // "list-column-header": { outer: [headerSlot] },
        },
        scroll: {
          horizontal: {
            precise: true,
          },
          vertical: {
            precise: true,
          },
        },
        templates: {
          "chart-timeline-grid-row-cell": chartTimelineGridRowCellTemplate,
          "list-column-row": listColumnRowTemplate,
          "chart-timeline-items": chartTimelineItemsTemplate,
          "chart-timeline-items-row-item": chartTimelineItemsRowItemTemplate,
        },
      };
      console.log(gstcElement.value);
      state = GSTC.api.stateFromConfig(config);
      globalThis.state = state;
      globalThis.config = config;
      gstc = GSTC({
        element: gstcElement.value,
        state,
      });
      globalThis.gstc = gstc;
      state.update("config.chart.time", (time) => {
        time.from = date("2021-7-31").startOf("day").valueOf();
        time.to = date("2023-12-01").endOf("month").valueOf();
        return time;
      });
    });
    onBeforeUnmount(() => {
      console.log("des");
      if (gstc) gstc.destroy();
    });
    const afterClose = () => {
      if (store.rowData.prepath) {
        const paths = store.rowData.prepath.split(",");
        paths.map((path) => {
          state.update("config.chart.items." + GSTCID(path), (a) => {
            a.dependant.push(store.rowData.id);
            return a;
          });
        });
      }
    };
    const submit = () => {
      state.update("config.list.rows." + store.rowData.id, (old) => {
        console.log(store.rowData);
        return store.rowData;
      });
      state.update("config.chart.items." + store.rowData.id, (old) => {
        console.log("ww", old);
        old.time.start = store.rowData.startTime + 3600 * 8 * 1000;
        old.time.end = store.rowData.startTime + 3600 * 20 * 1000;
        return old;
      });
      store.isModelShow = false;
      let upData = {
        allday: 0,
        code: "",
        dataend: "",
        datastart: "",
        id: 0,
        keypath: "",
        milestone: "",
        name: "",
        needday: 0,
        originalcode: "",
        parent: 0,
        parentId: 0,
        remark: "",
        responsible: "",
        selfId: 0,
      };
      upData.id = parseInt(store.rowData.id.split("-")[1]);
      upData.parent = parseInt(store.rowData.parentId.split("-")[1]);
      upData.name = store.rowData.task;
      upData.datastart = date(store.rowData.startTime).format("YYYY-MM-DD");
      upData.dataend = date(store.rowData.endTime).format("YYYY-MM-DD");
      upData.allday = store.rowData.taskTime;
      upData.code = store.rowData.code;
      updateMethod(upData);
      if (store.rowData.prepath) {
        const paths = store.rowData.prepath.split(",");
        paths.map((path) => {
          state.update("config.chart.items." + GSTCID(path), (a) => {
            a.dependant.push(store.rowData.id);
            console.log(a);
            return a;
          });
        });
      }
      store.rowData = {};
    };

    return {
      gstcElement,
      submit,
      afterClose,
    };
  },
};
</script>
<style>
.myselected {
  background-color: rgb(161, 171, 239);
}
.color1 {
  background-color: rgb(201, 143, 61);
}
.color2 {
  background-color: rgb(70, 92, 179);
}
.color3 {
  background-color: rgb(174, 204, 165);
}
.color4 {
  background-color: rgb(159, 198, 216);
}
.color5 {
  background-color: rgb(130, 234, 180);
}
.color6 {
  background-color: rgb(222, 139, 230);
}
/* .gstc__chart-timeline-grid-row-cell {
  border-right: 0;
  border-bottom: 0;
} */
.gstc__chart-timeline-items-row-item-label {
  display: block;
  overflow: visible !important;
  text-overflow: clip !important;
}
.my-items-slot {
  font-size: 14px;
}
.my-item-slot-content {
  display: block;
  width: 40px;
}
.gstc-wrapper {
  margin: 0;
  padding: 0;
}

.my_line_text1 {
  color: black;
  width: 1000px;
  position: relative;
  top: -30px;
  left: 20px;
}
.my_line_text2 {
  color: black;
  width: 1000px;
  position: relative;
  top: -40px;
  left: 40px;
}
.gstc__chart-timeline-dependency-lines-lines-line path {
  stroke: rgba(247, 165, 44, 0.9);
}
.my_line path {
  stroke: red;
}
.my_line_row {
  display: flex;
}

.arr_down {
  width: 0;
  height: 0;
  border: 5px solid black;
  border-color: black transparent transparent transparent;
}
.arr_right {
  width: 0;
  height: 0;
  border: 5px solid black;
  border-color: transparent transparent transparent black;
}
.arr_up {
  width: 0;
  height: 0;
  border: 5px solid black;
  border-color: transparent transparent black transparent;
}
</style>
